import React, { Component } from 'react';
import { connect } from 'react-redux';
import { Button,Card,Form,Input,message,Select,DatePicker } from 'antd';
import { ArrowLeftOutlined, } from '@ant-design/icons';
import { reqTeacherList,reqUpdateContent,reqAddContent ,reqAttributeList} from '../../../api'
import { saveContentListAction} from '../../../redux/action_creators/course_action';
import { saveTeacherAction } from '../../../redux/action_creators/user_action';
import { saveAttributeAction } from '../../../redux/action_creators/course_action';
import PicturesWall from '../../../components/util/picture_wall';
import RichTextEditor from '../../../components/util/rich_text_edit';
import dayjs from 'dayjs';
import moment from 'moment';
import './addUpdate.less';

const {Item} =Form;
const { Option } = Select;
const { RangePicker } = DatePicker;

@connect(
    (state)=>({
        contentList:state.course.contentList,
        teacherList:state.userList.teacherList,
        attributeList:state.course.attributeList
    }),
    {
        saveContentList:saveContentListAction,
        saveTeacherList:saveTeacherAction,
        saveAttributeList:saveAttributeAction
    }
)
class AddUpdate extends Component {
    state={
        operateType:'add',
        courseNum:'',
        courseName:'',
        courseRoom:'',
        courseType:'',
        courseWeek:'',
        courseTime:'',
        attributeId:'',
        teacherId:'',
        stopTime:'',
        courseDesc:'',
        courseStatus:'',
        courseDate:'',
        courseImg:'',
        price:'',
        id:'',
        teacherList:[],
        attributeList:[],
        contentList:[]
    }
    componentDidMount(){
        const { id } = this.props.match.params
        const { contentList,teacherList} = this.props
        // 获取讲师信息列表
        if(teacherList.length){
              this.setState({teacherList})
         }else{
            this.getTeacherList()
         }
        // 获取课程属性列表
        this.getAttributeList()
        // 获取课程信息列表
        if(id) {
            this.setState({operateType:'update'})
            if(contentList.length){
               let result = contentList.find((item)=>{
                   return item.id === parseInt(id)
               })
               if(result){
                    let stopTime 
                   if(result.stopTime){
                    stopTime = dayjs(result.stopTime).format('YYYY-MM-DD HH:mm:ss')
                   }
                   console.log(result);
                   this.setState({...result,stopTime})
                   this.textEditor.setDetail(result.courseDesc)
                    if(result.courseImg){
                        this.pictureWall.setFileList(result.courseImg.split(','))
                   }
               } 
            }else{
                const {courseImg,stopTime,courseDate,courseTime,courseDesc} = this.props.location.state.contentItem
                console.log(courseDate);
                const stopTimeNew = dayjs(stopTime).format('YYYY-MM-DD HH:mm:ss')
                this.setState({stopTime:stopTimeNew,courseDate,courseTime})
                this.textEditor.setDetail(courseDesc)
                 if(courseImg){
                    this.pictureWall.setFileList(courseImg.split(','))
                }
            }
        }else this.setState({operateType:'add'})
    }
    // 获取讲师信息列表
    getTeacherList = async () => {
        let result = await reqTeacherList()
        const { code,data,msg} = result
        // console.log(result);
        if(code === 200){
            this.setState({
                teacherList:data,
            })
            //   把用户列表保存到redux中
              this.props.saveTeacherList(data)
        }else{
            message.error(msg,1)      
        } 
     }
    // 获取课程分类列表
    getAttributeList= async ()=>{
        let result= await reqAttributeList()
        const { code, data, msg } = result
        if(code === 200){
        this.setState({attributeList:data})
        this.props.saveAttributeList(data)
        }else{
            message.error(msg,1)
        }
    }
    // 提交表单
    onFinish = async (values) => {
        // 从上传图片组件中获取图片地址数组
       let courseImg = this.pictureWall.getImgArr()
       let courseDesc = this.textEditor.getDetail()
       if(courseImg.length<1){
           message.error("请上传课程图片再提交",1)
           return;
       }
       if(courseDesc.length<9){
        message.error("请填写课程描述再提交",1)
        return;
       }
       console.log(courseDesc.length);
       let result
       const { courseDate,stopTime,courseTime } = this.state
       if(this.state.operateType === 'add'){
           const courseList = {...values,courseDate,courseDesc,courseTime,stopTime,courseImg}
           console.log(courseList);
            result = await reqAddContent({...courseList})
            const { code,data,msg } = result;
            if(code===200){
                message.success('添加成功！',1)
                let contentList = [...this.props.contentList]
                contentList.unshift(data[0])
                this.props.saveContentList(contentList)
                this.props.history.replace('/training/admin/course/content')
            }else{
                message.error(msg,1)
            }
        }else{
            console.log(values);
            const {id,courseStatus}= this.props.location.state.contentItem
            const courseList = {...values,courseDate,courseTime,stopTime,courseDesc,courseStatus,courseImg,id}
            console.log(courseList);
             result = await reqUpdateContent({...courseList})
             const { code,data,msg } = result;
             if(code===200){
                 message.success('修改成功',1)
                 let contentList = [...this.props.contentList]
                 contentList = contentList.map((item)=> parseInt(item.id) === data[0].id ? data[0] : item);
                 this.props.saveContentList(contentList)
                 this.props.history.replace('/training/admin/course/content')
             }else{
                 message.error(msg,1)
             }
        }
    };
    onChangeDate=(dates, dateStrings) =>{
        let courseDate =dateStrings.join(',')
        this.setState({courseDate});
        console.log(courseDate);
    }
    onChangeStopTime =(dates, dateStrings) =>{
        this.setState({stopTime:dateStrings});
        console.log(dateStrings);
    }
    onChangeCourseTime=(dates, dateStrings)=>{
        let courseTime =dateStrings.join(',')
        this.setState({courseTime});
        console.log(courseTime);
    }
    // 表单填写有误
    onFinishFailed = (errorInfo) => {
        console.log('Failed:', errorInfo);
        // message.error('表单有误，请检查！',1)
    };

    render() {
        const { operateType,teacherList,attributeList } = this.state
        const {courseNum,courseName,teacherId,courseRoom,courseType,courseDate,courseWeek,courseTime,attributeId,stopTime,courseDesc,price} = this.props.location.state.contentItem
        return (
            
                <Card 
                    title={
                        <div className="left-top">
                            <Button 
                                type="link" 
                                size="small"
                                onClick={()=>{this.props.history.goBack()}} 
                            >
                                <ArrowLeftOutlined/>
                            </Button>
                            <span>{operateType==='update'?'课程信息修改':'课程信息添加'}</span>
                        </div>
                    }          
                >
                <Form
                    labelCol= {{span: 2,}}
                    wrapperCol= {{span: 6}}
                    name="basic"
                    initialValues={{
                        remember: true,
                        
                    }}
                    onFinish={this.onFinish}
                    onFinishFailed={this.onFinishFailed}
                >
                    <Item label="课程编号"
                        name="courseNum"
                        initialValue={courseNum || ''}
                        rules={[{required: true,message: '课程编号不能为空',}]}>
                        <Input placeholder="课程编号"  allowClear disabled={operateType==="add"?false:true}/>
                    </Item>
                    <Item label="课程名称"
                        name="courseName"
                        initialValue={courseName || ''}
                        rules={[{required: true,message: '课程名称不能为空',}]} >
                        <Input placeholder="课程名称" allowClear />
                    </Item>
                    <Item label="授课讲师"
                        name="teacherId"
                        initialValue={teacherId }
                        rules={[{required: true,message: '请选择授课讲师',}]} >
                        <Select placeholder="请选择授课讲师" disabled={operateType==="add"?false:true}>
                        {teacherList.map((item)=>{
                            return  <Option key={item.id} value={item.id}>{item.username}</Option>
                        })}
                        </Select>
                    </Item>
                    <Item label="授课地点"
                        name="courseRoom"
                        initialValue={courseRoom || ''}
                        rules={[{required: true,message: '授课地点不能为空',}]} >
                        <Input placeholder="授课地点" allowClear/>
                    </Item> 
                    <Item label="课程价格"
                        name="price"
                        initialValue={price || ''}
                        rules={[{required: true,message: '课程价格不能为空',}]} >
                        <Input placeholder="单位：元" allowClear/>
                    </Item>     
                    <Item label="课程日期"
                        name="courseDate"
                        initialValue={courseDate?[moment(courseDate.split(',')[0], 'YYYY-MM-DD'), moment(courseDate.split(',')[1], 'YYYY-MM-DD')]:''}
                        rules={[{required: true,message: '课程日期不能为空',}]}  >
                        {/* <Input placeholder="2021-03-20至2021-06-30"/> */}
                       <RangePicker onChange={this.onChangeDate}/>
                    </Item>
                    <Item label="课程周期"
                        name="courseWeek"
                        initialValue={courseWeek || ''}
                        rules={[{required: true,message: '课程周期不能为空',}]} >
                        <Input placeholder="例如：周一、周三" allowClear/>
                    </Item>
                    <Item label="课程时间"
                        name="courseTime"
                        initialValue={courseTime?[moment(courseTime.split(',')[0], 'HH:mm'), moment(courseTime.split(',')[1], 'HH:mm')]:''}
                        rules={[{required: true,message: '课程时间不能为空',}]} >
                        <RangePicker picker="time" format="HH:mm"  onChange={this.onChangeCourseTime}/>
                    </Item>
                    <Item label="截止时间"
                          name="stopTime"
                          initialValue={stopTime?moment(dayjs(stopTime).format('YYYY-MM-DD HH:mm:ss'), 'YYYY-MM-DD HH:mm:ss'):''}
                          rules={[{required: true,message: '截止时间不能为空',}]}  
                      >
                        <DatePicker showTime  onChange={this.onChangeStopTime}/>
                    </Item>
                   
                    <Item label="课程类型"
                        name="courseType"
                        initialValue={courseType || ''}
                        rules={[{required: true,message: '课程类型不能为空',}]} >
                        <Input placeholder="如：入门、进阶、高级" allowClear/>
                    </Item>                 
                   <Item label="课程属性"
                        name="attributeId"
                        initialValue={attributeId||'' }
                        rules={[{required: true,message: '请选择课程属性',}]}  >
                         <Select placeholder="请选择性别" >
                        {attributeList.map((item)=>{
                            return  <Option key={item.id} value={item.id}>{item.attributeName}</Option>
                        })}
                        </Select>
                    </Item>
                    <Item label="课程描述"
                        name="courseDesc"
                        initialValue={courseDesc || ''}
                        wrapperCol= {{span: 10}}
                    >
                         <RichTextEditor ref={(textEditor)=>{this.textEditor = textEditor}}/>
                    </Item>
                    <Item label="课程照片"
                        name="courseImg"
                        wrapperCol= {{span: 12}} >
                        <PicturesWall ref={(pictureWall)=>{this.pictureWall = pictureWall}}/>
                    </Item>               
                    <Item  wrapperCol={{ offset: 2, span: 24}} >
                        <Button  type="primary" htmlType="submit" className="login-from-button">提交</Button>
                    </Item>
                </Form>
                </Card>
            
        )
    }
}
export default  AddUpdate;